package de.moc.android;

import java.io.BufferedReader;
import java.io.IOException;
//import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import de.moc.shared.Survey;

public class MOCConnection
{
	
	private URL targetURI;
	private String lastSurvey = ""; //Letzte Umfrage, zu der Abgestimmt wurde
	private String newSurvey = "";  //Aktuelle Umfrage
	private JSONParser parser = new JSONParser();
	
	public void setTargetURI(URL newTargetURI)
	{
		targetURI=newTargetURI;
	}
	public URL getTargetURI()
	{
		return targetURI;
	}	

	public Survey getSurvey()
	{
		
		Survey survey = null;
		String result = null;
		
		try
		{

			// Send data
			//String urlStr = targetURI + "hallo";

			URL url = targetURI; //new URL(urlStr);
			URLConnection conn = url.openConnection ();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1"));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null)
			{
				sb.append(line);
			}
			rd.close();
			result = sb.toString();
		} catch (Exception e)
		{
			return null;
		}
	
		survey = (Survey) parser.surveyfromJson(result);		
		
		
		if(survey.getId().equals(lastSurvey) || survey.getId().equals("11"))
		{
			
			return null;
		}
		
		newSurvey = survey.getId();
		
		return survey;
	}
	
	public void sendResult(String toSend)
	{
		
		HttpURLConnection urlc = null;
		try
		{
			urlc = (HttpURLConnection) targetURI.openConnection();
			try
			{
				urlc.setRequestMethod("POST");
			} catch (ProtocolException e)
			{
			}
			
			urlc.setDoOutput(true);
			urlc.setDoInput(true);
			urlc.connect();
			
			OutputStream out = urlc.getOutputStream();
			OutputStreamWriter writer = new OutputStreamWriter(out);

			try
			{
				writer.write(toSend);
				writer.flush();
				writer.close();
				out.close();
			} catch (IOException e)
			{
			}
			
            int responseCode = urlc.getResponseCode();
           
            if (responseCode == HttpURLConnection.HTTP_OK) {
            	//InputStream in = urlc.getInputStream();
            	lastSurvey = newSurvey;
            }
            

		} catch (IOException e)
		{
		}
		
	}
	
}